package com.infinitegroup.findmystuff.activities;

import java.util.List;
import java.util.Map;

import com.infinitegroup.findmystuff.R;
import com.infinitegroup.findmystuff.presenters.Constants;
import com.infinitegroup.findmystuff.presenters.ViewAllPresenter;
import com.infinitegroup.findmystuff.views.ViewAllView;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.PopupWindow;
import android.widget.Spinner;

/**
 *  Displays all the items in the database, can open a popup window to define search criteria, and then
 *  display all the items that match this criteria. Can also advance to the home screen.
 * 
 * @author Stephen
 *
 */
public class ViewAllItemsActivity extends Activity implements ViewAllView{
	
	private ViewAllPresenter presenter;
	private List<Map<String,String>> map;
	private PopupWindow pw;

	/**
	 * Handles the start of the activity, gets all the items in the databse from
	 * the presenter, and sets the listeners for the buttons on the screen.
	 */
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_viewall);
		presenter = new ViewAllPresenter(this);

		Button search = (Button) findViewById(R.id.viewall_search);
		Button returnButton = (Button) findViewById(R.id.activity_viewall_return);
		search.setOnClickListener(new OnClickListener() {			
			/**
			 * Handles the click of the search button.
			 */
			public void onClick(View v) {
				initiatePopupWindow();
			}
		});
		returnButton.setOnClickListener(new OnClickListener() {
			/**
			 * Handles the click of the return to home button.
			 */
			public void onClick(View v) {
				presenter.handleReturnToHomeClick();
			}
		});
	}

	/**
	 * Resumes the activity.
	 */
	public void onResume() {
	    super.onResume();  // Always call the superclass method first
	    
	    /*
	     * TO DO:
	     * 
	     * Based on the the information received from the filter screen set the values of the
	     * category, status and date variables. If the filter was not selected, keep it null.
	     * Then information the presenter of what these values were.
	     * The presenter will get the items to display, and this activity has to finally display them.
	     */
	    
	    String category = "", status = "", orderBy="";
	    //boolean date=false; //?
	    
	    // Get the items to display.
	 	map = presenter.getItemsToDisplay(category, status, orderBy, orderBy, orderBy);
	 	
	 	String itemString = generateItemString(map);
	 	((TextView) findViewById(R.id.viewall_itemfilltext)).setText(itemString);
	}
	
	/**
	 * To destroy activity when back button is pressed.
	 */
	public boolean onKeyDown(int keyCode, KeyEvent event)
	{
	    if ((keyCode == KeyEvent.KEYCODE_BACK)){
	        finish();
	    }
	    return super.onKeyDown(keyCode, event);
	}
	
	/**
	 * Changes a list of the items to display into a string.
	 * @param itemList List of items to display.
	 * @return String representation of the list of items to display.
	 */
	private String generateItemString(List<Map<String, String>> itemList) {
		String result = "";
		if (itemList!=null){
			for (Map<String,String> m : itemList){
				result = result + "Name: " + m.get("itemname") + " | " + m.get("status") + "\n" + "Category: " +m.get("category") + "\n" +
						" Date: " + m.get("date") + "\n";
			}
		}
		return result;
	}

	/**
	 * Fills in the screen with a list of items from the database.
	 */
	public void generateViewAllScreen(List<Map<String, String>> itemList) {
		String itemString = generateItemString(itemList);
	 	((TextView) findViewById(R.id.viewall_itemfilltext)).setText(itemString);
	}

	/**
	 * Displays inputed text as a popup message.
	 */
	public void displayMessage(String message) {
		Toast toast = Toast.makeText(this, message, Toast.LENGTH_LONG);
		toast.setGravity(Gravity.CENTER, 0, 0);
		toast.show();		
	}

	/**
	 * Ends the activity.
	 */
	public void end() {
		finish();	
	}
	
	/**
	 * Makes a popup window for search.
	 */
	private void initiatePopupWindow() {
	    try {
	        //We need to get the instance of the LayoutInflater, use the context of this activity
	        LayoutInflater inflater = (LayoutInflater) ViewAllItemsActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	        //Inflate the view from a predefined XML layout
	        View layout = inflater.inflate(R.layout.activity_filter,(ViewGroup) findViewById(R.id.popup_element));
	        // create a 300px width and 470px height PopupWindow
	        pw = new PopupWindow(layout, 300, 470, true);
	        // display the popup in the center
	        pw.showAtLocation(layout, Gravity.CENTER, 0, 0);
	 
	        Button submitButton = (Button) layout.findViewById(R.id.filter_submit);
	        Button cancelButton = (Button) layout.findViewById(R.id.filter_cancel);
	        
	        cancelButton.setOnClickListener(cancel_button_click_listener);
	        submitButton.setOnClickListener(submit_button_click_listener);
	        
	 
	    } 
	    catch (Exception e) {
	        e.printStackTrace();
	    }
	}
	 
	/**
	 * Handles a click of the submit button on the popup by getting the information from all the different
	 * search fields, giving this info to the presenter, and then closing the popup window.
	 */
	private OnClickListener submit_button_click_listener = new OnClickListener() {
	    public void onClick(View v) {
	    	System.out.println("Running submit listener");
	    	String itemname = "";
	    	
	    	if((((EditText) pw.getContentView().findViewById(R.id.filter_keyword)).getText().toString() != null)){
	    		itemname = ((EditText) pw.getContentView().findViewById(R.id.filter_keyword)).getText().toString();
	    	}
	    	System.out.println("Ran itemName");
	    	String location = "";
	    	
	    	if(((EditText) pw.getContentView().findViewById(R.id.filter_zipcode)).getText().toString() != null){
	    		location = ((EditText) pw.getContentView().findViewById(R.id.filter_zipcode)).getText().toString();
	    	}
			
	    	//since spinner isn't owrking we are deleting it and making it all by default for now
			//Spinner spinner1 = (Spinner) pw.getContentView().findViewById(R.id.categoryspinner);
			//String category = String.valueOf(spinner1.getSelectedItem());
			//if (category.equals("All")){
				String category = "";
			//}
			
			String status = "";
			RadioGroup statusRadioGroup = (RadioGroup)pw.getContentView().findViewById(R.id.radioButtonGroupStatus);

			int selectedStatus  = statusRadioGroup.getCheckedRadioButtonId();

			switch(selectedStatus){
			case R.id.filter_lostitem:
				status = Constants.ITEM_STATUS_LOST;
				break;
			case R.id.filter_founditem:
				status = Constants.ITEM_STATUS_FOUND;
				break;
			default:
				status = "";
			}

			String orderBy = "";
			RadioGroup DateRadioGroup = (RadioGroup) pw.getContentView().findViewById(R.id.radioButtonGroupStatus2);
			int selectedDate  = DateRadioGroup.getCheckedRadioButtonId();
			switch(selectedDate){
			case R.id.filter_ascending:
				orderBy = Constants.ORDERBY_DATE_ASC;
				break;
			case R.id.filter_datedescending:
				orderBy = Constants.ORDERBY_DATE_DESCENDING;
				break;
			default:
				orderBy = Constants.ORDERBY_DATE_DESCENDING;
			}
			presenter.handleFilterClick(itemname, category, status, location, orderBy);
			pw.dismiss();
	    }
	};
	
	/**
	 * Handles cancel button of the popup window by closing the window.
	 */
	private OnClickListener cancel_button_click_listener = new OnClickListener() {
	    public void onClick(View v) {
	        pw.dismiss();
	    }
	};
}
